<template>
  <div class="app-container">
    <!-- table 展示列表数据
    :key="tableKey"
    v-loading="listLoading"
    :data="list"
    @sort-change="sortChange"
    -->
    <el-table
      id="table"
      :key="tableKey"
      ref="singleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      max-height="700"
      highlight-current-row
      style="width: 100%;"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      @sort-change="sortChange"
    >
      <!-- 表格展开 expand, 展示 子列表,
      通常用于head / line_ids 结构的数据
      table_expand_show, table_expand
      -->
      <div v-if="table_expand_show">
        <el-table-column type="expand">
          <template slot-scope="{ row }">
            <el-table :data="row[table_expand.field]">
              <div v-if="debug">
                <el-table-column label="ID" prop="id" align="center" width="80">
                  <template slot-scope="{ row: row2 }">
                    <span>{{ row2.id }}</span>
                  </template>
                </el-table-column>
              </div>

              <el-table-column type="index" label="序号" width="50" />

              <el-table-column
                v-for="col in table_expand.columns"
                :key="col.name"
                :label="col.label"
                :width="col.width ? col.width : ''"
                align="center"
              >
                <template slot-scope="{ row: row2 }">
                  <span>{{ row2[col.name] }}</span>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
      </div>

      <!-- row id col -->

      <el-table-column type="index" label="序号" width="50" />

      <div v-if="debug">
        <div v-if="childFieldName">
          <el-table-column label="ID" prop="id" align="center" width="80">
            <template slot-scope="{ row }">
              <span>{{ row.id }}</span>
            </template>
          </el-table-column>
        </div>
        <div v-else>
          <el-table-column
            label="ID"
            prop="id"
            sortable="custom"
            align="center"
            width="80"
            :class-name="getSortClass('id')"
          >
            <template slot-scope="{ row }">
              <span>{{ row.id }}</span>
              <!-- <div>{{row}}</div> -->
            </template>
          </el-table-column>
        </div>
      </div>

      <!-- 根据 columns 循环, 展示其他 col -->
      <el-table-column
        v-for="col in columns"
        :key="col.name"
        :label="col.label"
        align="center"
        :width="col.width ? col.width : ''"
      >
        <template slot-scope="{ row }">
          <span v-if="col.type === 'boolean'">{{
            row[col.name] ? '是' : row[col.name] === false ? '否' : '未知'
          }}</span>
          <span v-else>{{ row[col.name] }}</span>
        </template>
      </el-table-column>

      <!-- 查看/编辑/新增 三个按钮
      checkHidden,handle,handleView,handleUpdate,handleDelete
      -->
      <el-table-column
        v-if="checkHidden2(handle)"
        label="操作"
        align="center"
        :width="handle.width ? handle.width : 330"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            v-if="checkHidden(handle, 'view', row)"
            type="primary"
            size="small"
            @click="handleView(row)"
          >
            {{
              handle && handle.view && handle.view.text
                ? handle.view.text
                : '查看'
            }}
          </el-button>
          <el-button
            v-if="checkHidden(handle, 'edit', row)"
            type="primary"
            size="small"
            @click="handleUpdate(row)"
          >
            {{
              handle && handle.edit && handle.edit.text
                ? handle.edit.text
                : '修改'
            }}
          </el-button>
          <el-button
            v-if="checkHidden(handle, 'remove', row)"
            type="danger"
            size="small"
            @click="handleDelete(row)"
          >
            {{
              handle && handle.remove && handle.remove.text
                ? handle.remove.text
                : '删除'
            }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看详情 dialogCardVisible,columns,detailData -->
    <el-dialog title="查看详情" :visible.sync="dialogCardVisible">
      <!-- 查看详情 属性字段, columns, detailData -->
      <el-form label-position="left">
        <el-row>
          <el-col v-for="col in columns" :key="col.name" :span="12">
            <el-form-item :label="`${col.label}:`" style="width: 366px">
              <span>{{ detailData[col.name] }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 查看详情 子列表, table_expand_show,table_expand, detailData -->
      <el-table
        v-if="table_expand_show"
        :data="detailData[table_expand.field]"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="ID" prop="id" align="center" width="80">
          <template slot-scope="{ row: row3 }">
            <span>{{ row3.id }}</span>
          </template>
        </el-table-column>

        <el-table-column
          v-for="col in table_expand.columns"
          :key="col.name"
          :label="col.label"
          align="center"
        >
          <template slot-scope="{ row: row3 }">
            <span>{{ row3[col.name] }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import odoo from '@/odooapi'

// import FileSaver from 'file-saver'
// import XLSX from 'xlsx'

export default {
  name: 'TableList',
  components: {},
  directives: {},
  filters: {},

  props: {
    modelName: { type: String, default: '' },
    listLoading: { type: Boolean, default: false },
    childFieldName: { type: String, default: '' },
    list: { type: Array, default: () => [] },
    detailPage: { type: String, default: undefined },
    detailsFunc: { type: Function, default: undefined }
  },

  data() {
    return {
      debug: odoo.debug,
      Model: undefined,
      head_id: undefined,
      headData: {},

      tableKey: 0,

      sortable: 'custom',

      table_expand: {},
      table_expand_show: true,

      listQuery: {
        page: 1,
        limit: 20,
        domain: {},

        order: 'id desc'
      },

      columns: [],
      // eslint-disable-next-line object-curly-spacing
      handle: { view: {}, edit: {}, remove: {} },

      dialogCardVisible: false,
      detailData: {}
    }
  },
  async created() {
    this.Model = odoo.env(this.modelName)

    if (this.childFieldName) {
      // eslint-disable-next-line object-curly-spacing
      const { child_configs = {} } = this.Model.configs
      this.columns = child_configs[this.childFieldName].columns || []
      // eslint-disable-next-line object-curly-spacing
      const { handle = { view: {}, edit: {}, remove: {} } } = child_configs[
        this.childFieldName
      ]

      this.handle = handle

      this.sortable = undefined
      this.table_expand_show = false
      // this.flashDataForDetailPage()
    } else {
      const {
        table_expand,
        columns,
        filterItems,
        // eslint-disable-next-line object-curly-spacing
        handle = { view: {}, edit: {}, remove: {} }
      } = this.Model.configs

      this.handle = handle
      this.columns = columns || []

      const domainItems = filterItems.reduce((acc, cur) => {
        acc[cur.name] = cur.default || undefined
        return acc
      }, {})

      this.listQuery.domain = domainItems || {}
      this.table_expand = table_expand || {}
      this.table_expand_show = !!table_expand
    }
  },

  methods: {
    exportCheck({ fileName }) {
      // console.log('xxxx, tab id', document.querySelector('#table'))
      // /* generate workbook object from table */
      // var wb = XLSX.utils.table_to_book(document.querySelector('#table'))
      // /* get binary string as output */
      // var wbout = XLSX.write(wb, {
      //   bookType: 'xlsx',
      //   bookSST: true,
      //   type: 'array'
      // })
      // try {
      //   FileSaver.saveAs(
      //     new Blob([wbout], { type: 'application/octet-stream' }),
      //     `${fileName}.xlsx`
      //   )
      //   console.log('保存成功！')
      // } catch (e) {
      //   if (typeof console !== 'undefined') console.log(e, wbout)
      //   console.log('保存失败！')
      // }
      // return wbout
    },

    setCurrentRow(row) {
      this.$refs.singleTable.setCurrentRow(row)
    },

    checkHidden2(handle) {
      // eslint-disable-next-line object-curly-spacing
      // const { view = {}, edit = {}, remove = {} } = handle

      return true

      // if (view.hidden && edit.hidden && remove.hidden) {
      //   return false
      // } else {
      //   return true
      // }
    },

    checkHidden(handle, type, row) {
      if (handle[type] && handle[type].hidden) {
        const hidden = handle[type].hidden
        const hidden2 =
          typeof hidden === 'function'
            ? hidden({ self: this.Model, rec: row })
            : hidden
        return !hidden2
      } else {
        return true
      }
    },

    handleView(row) {
      if (this.detailPage) {
        this.$router.push({
          path: this.detailPage,
          query: { id: row.id }
        })
      } else if (this.detailsFunc) {
        this.detailsFunc(row)
      } else {
        this.dialogCardVisible = true
        this.detailData = row
      }
    },

    handleUpdate(row) {
      this.$emit('handle-click', row, {
        field: this.childFieldName,
        handle: 'update'
      })
    },

    handleDelete(row) {
      this.$emit('handle-click', row, {
        field: this.childFieldName,
        handle: 'remove'
      })
    },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      // 改变排序条件
      if (order === 'ascending') {
        this.listQuery.order = 'id'
      } else {
        this.listQuery.order = 'id desc'
      }
      // 排序条件变了, 重置为首页, 刷新数据
      this.listQuery.page = 1
      // this.getData()
    },

    getSortClass: function(key) {
      // 根据排序条件 显示 排序符号

      const order = this.listQuery.order
      return order === `${key}`
        ? 'ascending'
        : order === `${key} desc`
        ? 'descending'
        : ''
    }
  }
}
</script>
